package uk.co.agileworks.bidpirate.test;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.hibernate.SessionFactory;
import org.junit.Ignore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.test.context.transaction.BeforeTransaction;

@Ignore
public class DbUnitTestBase extends SpringTestBase {

	private static boolean loaded = false;
	
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	private SessionFactory sessionFactory;
	
	@BeforeTransaction
	public void load() throws DatabaseUnitException, SQLException, IOException {
		if (!loaded) {
			DatabaseOperation.CLEAN_INSERT.execute(getConnection(),
					new FlatXmlDataSetBuilder().build(
							new File("src/test/resources/dbunit/dataset.xml")));
			loaded = true;
		}
	}

	protected ITable getResults(String query) {
		try {
			flush();
			return getConnection().createQueryTable("results", query);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}

	private void flush() {
		sessionFactory.getCurrentSession().flush();
	}

	private IDatabaseConnection getConnection() throws DatabaseUnitException {
		return new DatabaseConnection(DataSourceUtils.getConnection(dataSource));
	}
}
